new Vue({
  el: '#app',
  data: {
    ossImgUrl: ossImgUrl, //oss图片域名
    env: '', //判断环境
    cityData: [], //常住地址可选项
    typeData: [ //证件类型可选项
      {
        value: 1,
        text: '香港'
      },
      {
        value: 2,
        text: '澳门'
      },
      {
        value: 3,
        text: '台湾'
      },
      {
        value: 4,
        text: '外籍'
      }
    ],
    type: 1, //信息类型 1 企业基本信息 2 代办人信息
    enp_type: 2, //企业类型 1 个体户 2 企业
    enp_code_type: 2, //企业注册号类型 1 营业执照注册号 2 统一社会信用代码	
    enp_code: '', //注册号/信用代码
    enp_title: '', //企业名称
    enp_user: '', //法人/经营者
    enp_time_type: 0, //营业截止时间类型 1 长期 2 指定时间 默认0
    enp_lose_time: '', //营业截止时间
    enp_img: '', //营业执照照片
    zz_pic1: "", //营业执照照片1(接口不传)
    zz_pic2: "", //营业执照照片2(接口不传)
    zz_pic3: "", //营业执照照片3(接口不传)
    user_type: '', //证件类型 0 大陆 1 香港 2 澳门 3 台湾 4
    user_name: "", //证件类型中文(接口不传)
    user_number: '', //证件号
    user_front_img: '', //证件照正面
    user_verso_img: '', //证件照反面
    province_id: '', //省ID
    city_id: '', //市ID
    address: '', //常住地址
    flag: false, //下一步是否可点击
    isEdit: true //常住地址是否可编辑
  },
  created() {
    // 判断是否在小程序内
    var u = window.navigator.userAgent;
    var that = this;
    if (/MicroMessenger/i.test(u)) { //判断是否是微信环境
      wx.miniProgram.getEnv(res => {
        if (res.miniprogram) { // 小程序
          that.env = 'mp';
        }
      })
    }
    // 缓存地址栏 phone 参数
    if (getUrlParam("phone")) {
      local.set("phone", getUrlParam("phone"));
    }
    this.getAddressData();
  },
  mounted() {
    this.queryInfo();
  },
  destroyed() {},
  methods: {
    // 切换企业类型 1 个体户 2 企业
    switchEnpType: function (e) {
      this.enp_type = e;
      this.enp_title = "";
      this.enp_user = "";
      this.enp_time_type = 0;
      this.enp_lose_time = "";
      this.user_type = "";
      this.user_number = "";
      this.user_front_img = "";
      this.user_verso_img = "";
      this.province_id = "";
      this.city_id = "";
      this.address = "";
      this.queryInfo();
      this.mustClick();
    },
    // 切换企业注册号类型 1 营业执照注册号 2 统一社会信用代码	
    switchEnpCodeType: function (e) {
      this.enp_code_type = e
      this.enp_code = ""
      this.mustClick();
    },
    // 验证营业执照注册号、统一社会信用代码
    verifyEnpcode: function () {
      this.mustClick();
      if (!this.enp_code) {
        return
      }
      switch (this.enp_code_type) {
        case 1: //营业执照注册号
          if (this.enp_code.replace(/\s*/g, "").length != 15) {
            mui.toast('营业执照注册号为15位');
            this.enp_code = "";
          }
          break;
        case 2: //统一社会信用代码
          if (this.enp_code.replace(/\s*/g, "").length != 18) {
            mui.toast('统一社会信用代码为18位');
            this.enp_code = "";
          } else {
            this.enp_code = this.enp_code.toUpperCase();
          }
          break;
      }
    },
    // 切换营业截止时间类型 1 长期 2 指定时间
    switchEnpTimeType: function (e) {
      this.enp_time_type = e
      this.enp_lose_time = ""
      this.mustClick();
    },
    // 选择营业截止日期
    selectDate: function () {
      document.activeElement.blur(); //收起键盘
      var that = this
      var dtPicker = new mui.DtPicker({
        "type": "date",
        "endDate": new Date(2050, 12, 31), //设置结束日期
      });
      dtPicker.show(function (e) {
        var arr = [e.y.value, e.m.value, e.d.value]
        that.enp_lose_time = arr.join("-")
        that.mustClick();
      });
    },

    // 上传照片通用方法
    upLoad: async function (inputName, type) {
      var inputDOM = this.$refs[inputName];
      var file = inputDOM.files[0]
      //判断是否是图片类型
      if (!/image\/\w+/.test(file.type)) {
        mui.toast("只能选择图片");
        return false;
      }
      var base64 = await this.repairPhoto(file, 0.9, 720);
      switch (type) {
        case 1: //营业执照1
          this.zz_pic1 = base64 //预览页面上预留一个img元素，载入base64
          var url = await this.uploadHttp(base64)
          this.zz_pic1 = httpImgUrl + url;
          break;
        case 2: //营业执照2
          this.zz_pic2 = base64 //预览页面上预留一个img元素，载入base64
          var url = await this.uploadHttp(base64)
          this.zz_pic2 = httpImgUrl + url;
          break;
        case 3: //营业执照3
          this.zz_pic3 = base64 //预览页面上预留一个img元素，载入base64
          var url = await this.uploadHttp(base64)
          this.zz_pic3 = httpImgUrl + url;
          break;
        case 4: //证件照正面
          this.user_front_img = base64 //预览页面上预留一个img元素，载入base64
          var url = await this.uploadHttp(base64)
          this.user_front_img = httpImgUrl + url;
          break;
        case 5: //证件照反面
          this.user_verso_img = base64 //预览页面上预留一个img元素，载入base64
          var url = await this.uploadHttp(base64)
          this.user_verso_img = httpImgUrl + url;
          break;
      }
      this.picJc();
    },
    // 整体调用
    repairPhoto: async function (file, num, w) {
      const result = await this.isNeedFixPhoto(file);
      const resultBase64 = await this.file2Base64(file);
      const Orientation = result.Orientation;
      const numb = num || 1;
      if (result.flag) { // 处理旋转
        return await this.best4Photo(resultBase64, Orientation, numb, w)
      } else { // 不处理旋转
        return await this.best4Photo(resultBase64, 1, numb, w)
      }
    },
    // 压缩处理选中的方法
    best4Photo: function (resultBase64, Orientation, num, w) {
      return new Promise(function (resolve, reject) {
        var image = new Image();
        image.src = resultBase64;
        image.onload = function () {
          var imgWidth = w;
          var imgHeight = w * this.height / this.width; //获取图片宽高
          var canvas = document.createElement("canvas");
          var ctx = canvas.getContext('2d');
          canvas.width = imgWidth;
          canvas.height = imgHeight;
          if (Orientation && Orientation != 1) {
            switch (Orientation) {
              case 6: // 旋转90度
                canvas.width = imgHeight;
                canvas.height = imgWidth;
                ctx.rotate(Math.PI / 2);
                ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
                break;
              case 3: // 旋转180度
                ctx.rotate(Math.PI);
                ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);
                break;
              case 8: // 旋转-90度
                canvas.width = imgHeight;
                canvas.height = imgWidth;
                ctx.rotate(3 * Math.PI / 2);
                ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
                break;
            }
          } else {
            ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
          }
          const result = canvas.toDataURL("image/jpeg", num);
          resolve(result)
        }
      })
    },
    // 上传图片到服务器
    uploadHttp: function (base64) {
      var filename = new Date().getTime() + "_" + (Math.random() * 100000).toFixed(0);
      return new Promise(function (resolve, reject) {
        post("api/upload/base64", {
          file: base64,
          filename: filename,
          dirPath: 'credentials'
        }).then(function (res) {
          var url = res.data.url;
          resolve(url)
        })
      })
    },
    // 判断图片是否需要旋转
    isNeedFixPhoto: function (file) {
      return new Promise(function (resolve, reject) {
        EXIF.getData(file, function () {
          var Orientation = EXIF.getTag(this, 'Orientation');
          if (Orientation && Orientation != 1) {
            //图片角度不正确
            resolve({
              flag: true,
              Orientation: Orientation
            })
          } else {
            //不需处理直接上传
            resolve({
              flag: false,
              Orientation: Orientation
            })
          }
        })
      })
    },
    // 将file文件 读成base64码 
    file2Base64: function (file) {
      return new Promise(function (resolve, reject) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (ev) {
          resolve(ev.target.result);
        }
      })
    },
    // 删除照片通用方法
    deletePic: function (type) {
      switch (type) {
        case 1: //营业执照1
          this.zz_pic1 = "";
          break;
        case 2: //营业执照2
          this.zz_pic2 = "";
          break;
        case 3: //营业执照3
          this.zz_pic3 = "";
          break;
        case 4: //证件照正面
          this.user_front_img = "";
          break;
        case 5: //证件照反面
          this.user_verso_img = "";
          break;
      }
      this.picJc();
    },
    // 检测照片是否上传
    picJc: function () {
      var urlArr = [this.zz_pic1, this.zz_pic2, this.zz_pic3]
      var arr = []
      urlArr.forEach(function (item) {
        if (item) {
          arr.push(item.split('/').slice(3).join('/'))
        }
      })
      this.enp_img = arr.toString()
      this.mustClick();
    },
    // 选择证件类型 0大陆(身份证) 1香港 2澳门 3台湾 4外籍(暂时未用 )
    selectType: function () {
      document.activeElement.blur(); //收起键盘
      var that = this
      var selectorFr = new mui.PopPicker();
      selectorFr.setData(that.typeData)
      selectorFr.show(function (item) {
        that.user_type = item[0].value
        that.user_name = item[0].text
        that.mustClick();
      })
    },
    //证件号验证位数验证（8位到18位）
    verifyId: function () {
      if (!this.user_number) {
        return
      }
      if (this.user_number.length < 8) {
        mui.toast('证件号必须在8位到18位之间');
        this.user_number = "";
      }
      this.mustClick();
    },
    // 接口获取地址可选项
    getAddressData: function () {
      var that = this;
      return new Promise(function (resolve, reject) {
        post("api/address/index").then(function (res) {
          var data = [...res.data];
          var cityData = [];
          data.map(function (item) {
            var child = [];
            item.children.map(function (el) {
              child.push({
                id: el.id,
                text: el.name,
                pid: el.pid,
                children: el.children
              })
            })
            cityData.push({
              id: item.id,
              text: item.name,
              pid: item.pid,
              children: child
            })
          });
          that.cityData = cityData;
          resolve(cityData);
        })
      })
    },
    // 选择常住地址
    selectAddress: function () {
      if (!this.isEdit) {
        return
      }
      document.activeElement.blur(); //收起键盘
      var that = this
      var selector = new mui.PopPicker({
        layer: 2 //显示列数
      })
      selector.setData(that.cityData)
      selector.show(function (item) {
        that.province_id = item[0].id; //省ID
        that.city_id = item[1].id //市ID
        that.address = item[0].text + " " + item[1].text; //常住地址
        that.mustClick();
      })
    },
    // 失去焦点验证下一步是否可点击
    mustClick: function () {
      if (!this.enp_type) {
        this.flag = false
      } else if (!this.enp_code_type) {
        this.flag = false
      } else if (!this.enp_code) {
        this.flag = false
      } else if (!this.enp_title) {
        this.flag = false
      } else if (!this.enp_user) {
        this.flag = false
      } else if (this.enp_type == 2 && !this.enp_time_type) {
        this.flag = false
      } else if (this.enp_type == 2 && this.enp_time_type == 2 && !this.enp_lose_time) { //指定时间类型&&enp_lose_time==""
        this.flag = false
      } else if (!this.enp_img) {
        this.flag = false
      } else if (!this.user_number) {
        this.flag = false
      } else if (!this.user_front_img) {
        this.flag = false
      } else if (!this.user_verso_img) {
        this.flag = false
      } else if (!this.province_id && !this.city_id) {
        this.flag = false
      } else {
        this.flag = true
      }
    },
    // 下一步
    submit: function () {
      var that = this;
      if (!this.flag) {
        return
      }
      post("api/enps", {
        enp_type: this.enp_type,
        enp_code_type: this.enp_code_type,
        enp_code: this.enp_code.replace(/\s*/g, ""),
        enp_title: this.enp_title.replace(/\s*/g, ""),
        enp_user: this.enp_user.replace(/\s*/g, ""),
        enp_lose_time: this.enp_lose_time,
        enp_img: this.enp_img,
        user_type: 0,
        user_front_img: this.user_front_img.split('/').slice(3).join('/'), //去除域名
        user_verso_img: this.user_verso_img.split('/').slice(3).join('/'), //去除域名
        province_id: this.province_id,
        city_id: this.city_id,
        user_number: this.user_number.replace(/\s*/g, ""),
        enp_time_type: this.enp_time_type ? this.enp_time_type : 0,
      }).then(function (res) {
        if (res.data) {
          if (res.data.auth_status == 3) { //认证成功
            window.location.href = "operator_rz.html";
          } else if (res.data.auth_status == 1) {
            mui.toast("认证中请稍后重试");
          } else {
            mui.toast("企业实名认证失败");
          }
        }
      })
    },
    /* 第二次的流程 */
    // 查询页面信息
    queryInfo: function () {
      var that = this;
      // isSelf字段随便传
      get("api/enp/" + this.type + "/user/1").then(function (res) {
        if (JSON.stringify(res.data) != "{}" && res.data) {
          var data = res.data;
          that.isEdit = res.data.is_edit;
          that.fillData(data);
        }
      })
    },
    // 填入查询的数据
    fillData: async function (data) {
      var that = this;
      if (data.agency) {
        this.enp_type = data.agency.enp_type;
        this.enp_code_type = data.agency.enp_code_type;
        this.enp_code = data.agency.enp_code;
        this.enp_title = data.agency.enp_title;
        this.enp_user = data.agency.enp_user;
        this.enp_time_type = data.agency.enp_time_type;
        this.enp_lose_time = data.agency.enp_lose_time;
        this.enp_img = data.agency.enp_img;
        this.user_type = data.agency.user_type
        this.user_number = data.agency.user_number;
        this.user_front_img = data.agency.user_front_img ? httpImgUrl + data.agency.user_front_img : "";
        this.user_verso_img = data.agency.user_verso_img ? httpImgUrl + data.agency.user_verso_img : "";
      }

      var imgUrl = this.enp_img.split(',');
      this.zz_pic1 = imgUrl[0] ? httpImgUrl + imgUrl[0] : '';
      this.zz_pic2 = imgUrl[2] ? httpImgUrl + imgUrl[2] : '';
      this.zz_pic3 = imgUrl[3] ? httpImgUrl + imgUrl[3] : '';
      this.typeData.map(function (item) {
        if (item.value == that.user_type) {
          that.user_name = item.text;
        }
      });
      this.province_id = data.province_id;
      this.city_id = data.city_id;
      this.getAddressData().then(function (res) {
        var cityName = [];
        res.map(function (item) {
          if (item.id == that.province_id) {
            cityName.push(item.text)
          }
          if (item.children) {
            item.children.map(function (el) {
              if (el.id == that.city_id) {
                cityName.push(el.text)
              }
            })
          }
        });
        that.address = cityName.join("");
      })
      this.mustClick(); //检测下一步按钮是否高亮
    }
  }
})